<template>
  <div class="header-with-back">
    <div class="back-nav" @click="goToJSJL">
      <van-icon name="arrow-left" />
      <span style="font-size: 1.2rem">{{title}}</span>
    </div>
  </div>
  <div class="bottom-van">
    <div class="bottom-van-top">
      <div class="content">
        <div class="img-container">
          <!-- 资源信息卡片 -->
          <van-cell-group inset class="video-info">

            <van-cell>
              <template #title>
                <div class="uploader-cell">
                  <van-image
                      round
                      width="5vh"
                      height="5vh"
                      :src="getSafeUserImg(item?.userImg)"
                      class="uploader-avatar"
                  />
                  <span class="uploader-name">{{item?.userName || '未知用户'}}</span>
                  <van-icon
                      class="download-icon"
                      @click="handleDownload"
                  >下载</van-icon>
                </div>
              </template>
            </van-cell>

            <van-cell>
              <template #title>
                <h2 class="video-title">{{item?.resourceName || '未命名资源'}}</h2>
              </template>
            </van-cell>


            <van-cell title="文章" :label="item?.resourceDescription || '暂无描述'" />

            <!-- 视频类型显示视频播放器 -->
            <div v-if="isVideo(item?.storagePath)" class="video-container">
              <video
                  controls
                  width="100%"
                  class="video-player"
              >
                <source :src="getSafeUrl(item?.storagePath)" :type="getVideoType(item?.storagePath)">
                您的浏览器不支持视频播放
              </video>
            </div>

            <!-- 图片类型直接显示原图 -->
            <van-image
                v-else-if="isImage(item?.storagePath)"
                width="100%"
                height="160"
                fit="contain"
                radius="10px"
                :src="getSafeUrl(item?.storagePath)"
            >
              <template v-slot:loading>
                <van-loading type="spinner" size="20" />
              </template>
              <template v-slot:error>加载图片失败</template>
            </van-image>

            <!-- 非图片文件显示对应类型的图标 -->
            <van-image
                v-else
                width="100%"
                height="160"
                fit="contain"
                radius="10px"
                :src="getFileIcon(item?.storagePath)"
            >
              <template v-slot:error>无法显示文件预览</template>
            </van-image>

          </van-cell-group>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { computed } from "vue";
import { useUserStore } from '../../Store/modules/userinfo/UserInfo'
import { useTeachingResourceStore } from '../../Store/modules/resource/TeachingResource.ts'

const userStore = useUserStore()
const useTeachingResource = useTeachingResourceStore();
const router = useRouter();
const title = computed(() => router.currentRoute.value.meta.title || "资源详情");


const item = computed(() => useTeachingResource.fetchResourceDetail || {});
// console.log(item.value)

// 添加删除加载状态
const deleteLoading = ref(false);

// 返回到教师交流
function goToJSJL() {
  router.push('/resourceshare');
}

// 安全获取用户头像
const getSafeUserImg = (url) => {
  try {
    if (!url) return '/src/Assets/img/default-avatar.jpg';
    // 验证URL格式
    if (typeof url === 'string' && (url.startsWith('http') || url.startsWith('/'))) {
      return url;
    }
    return '/src/Assets/img/default-avatar.jpg';
  } catch {
    return '/src/Assets/img/default-avatar.jpg';
  }
};

// 安全获取URL
const getSafeUrl = (url) => {
  try {
    if (!url) return '';
    // 简单的URL验证
    if (typeof url === 'string' && (url.startsWith('http') || url.startsWith('/') || url.startsWith('blob:'))) {
      return url;
    }
    return '';
  } catch {
    return '';
  }
};

// 判断是否为图片
const isImage = (url) => {
  try {
    if (!url) return false;
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
    const cleanUrl = String(url).split('?')[0].split('#')[0].toLowerCase();
    return imageExtensions.some(ext => cleanUrl.endsWith(ext));
  } catch {
    return false;
  }
};

// 判断是否为视频
const isVideo = (url) => {
  try {
    if (!url) return false;
    const videoExtensions = ['.mp4', '.webm', '.ogg', '.mov', '.avi', '.wmv'];
    const cleanUrl = String(url).split('?')[0].split('#')[0].toLowerCase();
    return videoExtensions.some(ext => cleanUrl.endsWith(ext));
  } catch {
    return false;
  }
};

// 获取视频类型
const getVideoType = (url) => {
  try {
    if (!url) return 'video/mp4';
    const cleanUrl = String(url).split('?')[0].split('#')[0].toLowerCase();
    const extension = cleanUrl.split('.').pop();

    const typeMap = {
      mp4: 'video/mp4',
      webm: 'video/webm',
      ogg: 'video/ogg',
      mov: 'video/quicktime',
      avi: 'video/x-msvideo',
      wmv: 'video/x-ms-wmv'
    };

    return typeMap[extension] || 'video/mp4';
  } catch {
    return 'video/mp4';
  }
};

// 获取文件类型图标
const getFileIcon = (url) => {
  try {
    if (!url) return '/src/Assets/img/default.jpg';

    // 处理URL中的查询参数和哈希
    const cleanUrl = String(url).split('?')[0].split('#')[0].toLowerCase();
    const extension = cleanUrl.split('.').pop();

    const iconMap = {
      pdf: "https://cqust-ted.oss-cn-chengdu.aliyuncs.com/41bfab0a-823b-472e-9867-24ac7b3af901.jpg",
      doc: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/d23895f5-c825-4b13-8c61-dd88f504054f.jpeg',
      docx: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/ac21223d-ca2a-49ce-87a6-860fd823ad60.jpeg',
      ppt: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/3a9c95ff-dd1d-4e8f-8e21-fdaa83da197b.jpg',
      pptx: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/f02f030a-258e-4498-b0fa-c724224f2d53.jpg',
      xls: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/362bb9eb-5f6e-4ead-bd2d-86c7998666fc.jpeg',
      xlsx: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/362bb9eb-5f6e-4ead-bd2d-86c7998666fc.jpeg',
      mp4: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/bd36d4e6-75ec-4747-ab65-74ca5bc302ae.jpeg',
      zip: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/1c3b0823-c334-4358-89b5-ba2f3b7c9120.jpg',
      rar: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/c1cab020-560c-47d2-8123-279bf7b5b41f.jpeg',
      default: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/caf4d5aa-ae6f-49b3-a888-e93b80307e5c.jpg'
    };

    return iconMap[extension] || iconMap.default;
  } catch {
    return 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/caf4d5aa-ae6f-49b3-a888-e93b80307e5c.jpg';
  }
};

// 下载资源
const handleDownload = async () => {
  try {
    if (!item.value?.storagePath) {
      showToast('没有可下载的资源');
      return;
    }

    // 创建一个隐藏的<a>标签用于下载
    const link = document.createElement('a');
    link.href = item.value.storagePath;

    // 从URL中提取文件名，如果没有则使用资源名称
    const fileName = item.value.storagePath.split('/').pop() ||
        item.value.resourceName ||
        `resource_${Date.now()}`;

    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    showToast('开始下载');
  } catch (error) {
    console.error('下载失败:', error);
    showToast('下载失败');
  }
};
</script>

<style scoped>
.header-with-back {
  height: 40px;
  background-color: #f8f8f8;
  padding: 10px;
  text-align: left;
  font-size: 20px;
  color: #682757;
  line-height: 40px;
  overflow: hidden;
  min-width: 100%;
  position: fixed;
  z-index: 999;
}

.back-nav {
  position: fixed;
  left: 1%;
  top: 1.25%;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: rgb(83, 30, 88);
  padding: 0.5rem;
  z-index: 10;
  font-size: 0.9rem;
}

.header-with-back .van-icon {
  position: static;
  font-size: 1.35rem;
}

.content {
  padding-top: 18%;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.img-container {
  padding: 16px 0;
}

.video-info {
  margin-bottom: 16px;
}

.video-title {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #323233;
}

:deep(.van-image) {
  padding-top: 1rem;
  padding-left: 5px;
  aspect-ratio: 16/9;
  object-fit: cover;
}

.bottom-van {
  border-top: #D9D6D6FC solid 2px;
}

/* 上传者信息样式 */
.uploader-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.uploader-avatar {
  flex-shrink: 0;
}

.uploader-name {
  font-size: 14px;
  color: #323233;
  display: flex;
  align-items: center;
  height: 5%;
  margin-top: 3vh;
}

/* 视频播放器样式 */
.video-container {
  padding: 1rem 5%;
  width: 90%;
  margin: 0 auto;
}

.video-player {
  width: 100%;
  border-radius: 10px;
  background-color: #000;
  aspect-ratio: 16/9;
}

:deep(.van-cell-group--inset) {
  margin: 0 16px;
  padding-bottom: 5%;
}

:deep(.van-cell) {
  padding: 12px 16px;
}

/* 下载按钮样式 */
.download-icon {
  font-size: 15px;
  color: rgb(83, 30, 88);
  cursor: pointer;
  margin-left: 50%;
}
</style>
